package com.hitqz.robot.driver.netty.client;

import com.hitqz.robot.driver.netty.handler.RobotControllerMessageHandler;
import com.hitqz.robot.driver.netty.protocol.decoder.RobotControllerDecoder;
import com.hitqz.robot.driver.netty.protocol.encoder.RobotControllerEncoder;
import com.hitqz.robot.driver.util.SourceEnum;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2023/8/3
 */
@Slf4j
public class RobotControllerClient {
    public static void connect(String host, Integer port, SourceEnum sourceEnum) throws Exception {
        //log.info("start connect to  controller {}, {} {} ", host,  port, sourceEnum);
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端的服务启动助手完成相应配置
        Bootstrap b = new Bootstrap();

        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.TCP_NODELAY, true)
                //.option(ChannelOption.SO_BACKLOG, 2048*10)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 4096*10, 65536))
                .option(ChannelOption.SO_KEEPALIVE,Boolean.TRUE);

        ChannelFuture future;
        // 进行连接
        try {
            synchronized (b) {
                b.handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) {
                        //
                        //ByteBuf delimiter = Unpooled.copiedBuffer(new byte[] {
                        //        0x5A
                        //});
                        //channel.pipeline().addLast(new DelimiterBasedFrameDecoder(4096*100, delimiter));

                        channel.pipeline().addLast("encoder",new RobotControllerEncoder());
                        channel.pipeline().addLast("decoder",new RobotControllerDecoder());
                        channel.pipeline().addLast(new LengthFieldPrepender(2));
                        channel.pipeline().addLast(new RobotControllerMessageHandler(sourceEnum));


                    }
                });
                future = b.connect(host, port);
            }
            future.sync();
            //关闭连接(异步非阻塞)
            future.channel().closeFuture().sync();
        } catch (Throwable t) {
            group.shutdownGracefully().sync();
            //log.info("{}, {} connect failed and reconnect", host, port);
            TimeUnit.SECONDS.sleep(5);
            //log.info("重新进行连接");
            RobotControllerClient.connect(host, port, sourceEnum);
        }
    }





}
